package com.chongchong.online.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.chongchong.common.constant.ErrorCodeEnum;
import com.chongchong.common.tool.CommonUtil;
import com.chongchong.common.validator.UpdateGroup;
import com.chongchong.core.mp.object.MyModelUtil;
import com.chongchong.core.mp.object.MyOrderParam;
import com.chongchong.core.mp.object.MyRelationParam;
import com.chongchong.core.mp.support.Query;
import com.chongchong.core.tool.api.R;
import com.chongchong.online.dto.OnlineVirtualColumnDto;
import com.chongchong.online.entity.OnlineVirtualColumn;
import com.chongchong.online.entity.constant.VirtualType;
import com.chongchong.online.service.IOnlineVirtualColumnService;
import com.chongchong.online.vo.OnlineVirtualColumnVo;
import com.chongchong.online.wrapper.OnlineVirtualColumnWrapper;
import io.swagger.annotations.Api;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.validation.groups.Default;
import java.util.List;

/**
 * 虚拟字段操作控制器类。
 *
 * @author Jerry
 * @date 2021-06-06
 */
@Api(tags = "虚拟字段操作接口")
@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping("/onlinevirtualcolumn")
public class OnlineVirtualColumnController {

    private IOnlineVirtualColumnService onlineVirtualColumnService;

    /**
     * 新增虚拟字段数据。
     *
     * @param onlineVirtualColumnDto 新增对象。
     * @return 应答结果对象，包含新增对象主键Id。
     */
    @ApiOperationSupport(ignoreParameters = {"onlineVirtualColumnDto.virtualColumnId"})
    @PostMapping("/save")
    public R<Long> add(@RequestBody OnlineVirtualColumnDto onlineVirtualColumnDto) {
        String errorMessage = CommonUtil.getModelValidationError(onlineVirtualColumnDto);
        if (errorMessage != null) {
			return R.fail(errorMessage);
        }
        OnlineVirtualColumn onlineVirtualColumn =
                MyModelUtil.copyTo(onlineVirtualColumnDto, OnlineVirtualColumn.class);
        R<Void> verifyResult = this.doVerify(onlineVirtualColumn, null);
        if (!verifyResult.isSuccess()) {
            return R.fail(verifyResult.getMsg());
        }
        onlineVirtualColumn = onlineVirtualColumnService.saveNew(onlineVirtualColumn);
        return R.data(onlineVirtualColumn.getVirtualColumnId());
    }

    /**
     * 更新虚拟字段数据。
     *
     * @param onlineVirtualColumnDto 更新对象。
     * @return 应答结果对象。
     */
    @PostMapping("/update")
    public R<Void> update(@RequestBody OnlineVirtualColumnDto onlineVirtualColumnDto) {
        String errorMessage = CommonUtil.getModelValidationError(
                onlineVirtualColumnDto, Default.class, UpdateGroup.class);
        if (errorMessage != null) {
			return R.fail(errorMessage);
        }
        OnlineVirtualColumn onlineVirtualColumn =
                MyModelUtil.copyTo(onlineVirtualColumnDto, OnlineVirtualColumn.class);
        OnlineVirtualColumn originalOnlineVirtualColumn =
                onlineVirtualColumnService.getById(onlineVirtualColumn.getVirtualColumnId());
        if (originalOnlineVirtualColumn == null) {
            errorMessage = "数据验证失败，当前虚拟字段并不存在，请刷新后重试！";
			return R.fail(errorMessage);
        }
        R<Void> verifyResult = this.doVerify(onlineVirtualColumn, originalOnlineVirtualColumn);
        if (!verifyResult.isSuccess()) {
            return R.fail(verifyResult.getMsg());
        }
        if (!onlineVirtualColumnService.update(onlineVirtualColumn, originalOnlineVirtualColumn)) {
            return R.fail(ErrorCodeEnum.DATA_NOT_EXIST.getErrorMessage());
        }
        return R.data(null);
    }

    /**
     * 删除虚拟字段数据。
     *
     * @param virtualColumnId 删除对象主键Id。
     * @return 应答结果对象。
     */
    @PostMapping("/remove")
    public R<Void> delete(@RequestParam Long virtualColumnId) {
        String errorMessage;
        if (CommonUtil.existBlankArgument(virtualColumnId)) {
            return R.fail(ErrorCodeEnum.ARGUMENT_NULL_EXIST.getErrorMessage());
        }
        // 验证关联Id的数据合法性
        OnlineVirtualColumn originalOnlineVirtualColumn = onlineVirtualColumnService.getById(virtualColumnId);
        if (originalOnlineVirtualColumn == null) {
            errorMessage = "数据验证失败，当前虚拟字段并不存在，请刷新后重试！";
			return R.fail(errorMessage);
        }
        if (!onlineVirtualColumnService.remove(virtualColumnId)) {
            errorMessage = "数据操作失败，删除的对象不存在，请刷新后重试！";
			return R.fail(errorMessage);
        }
        return R.data(null);
    }

    /**
     * 列出符合过滤条件的虚拟字段列表。
     *
     * @param onlineVirtualColumnDtoFilter 过滤对象。
     * @param orderParam                   排序参数。
     * @param query                    分页参数。
     * @return 应答结果对象，包含查询结果集。
     */
    @GetMapping("/list")
	public R<IPage<OnlineVirtualColumnVo>> list(OnlineVirtualColumnDto onlineVirtualColumnDtoFilter,
												MyOrderParam orderParam, Query query) {
		OnlineVirtualColumn onlineVirtualColumnFilter =
			MyModelUtil.copyTo(onlineVirtualColumnDtoFilter, OnlineVirtualColumn.class);
		String orderBy = MyOrderParam.buildOrderBy(orderParam, OnlineVirtualColumn.class);
		List<OnlineVirtualColumn> onlineVirtualColumnList =
			onlineVirtualColumnService.getOnlineVirtualColumnListWithRelation(onlineVirtualColumnFilter, orderBy);

//		IPage<OnlineTable> pages = onlineTableService.page(Condition.getPage(query), Condition.getQueryWrapper(flowWorkOrder));

		IPage<OnlineVirtualColumn> pages = new Page<>(query.getCurrent(), query.getSize());
		pages.setRecords(onlineVirtualColumnList);

		return R.data(OnlineVirtualColumnWrapper.build().pageVO(pages));
	}

	/**
	 * 列出符合过滤条件的虚拟字段列表。
	 *
	 * @param onlineVirtualColumn 过滤对象。
	 * @return 应答结果对象，包含查询结果集。
	 */
	@GetMapping("/listNoPage")
	public R<List<OnlineVirtualColumnVo>> listNoPage( OnlineVirtualColumn onlineVirtualColumn) {
		List<OnlineVirtualColumn> onlineVirtualColumnList =
			onlineVirtualColumnService.getOnlineVirtualColumnListWithRelation(onlineVirtualColumn, null);

		return R.data(OnlineVirtualColumnWrapper.build().listVO(onlineVirtualColumnList));
	}

    /**
     * 查看指定虚拟字段对象详情。
     *
     * @param virtualColumn 指定对象主键Id。
     * @return 应答结果对象，包含对象详情。
     */
    @GetMapping("/view")
    public R<OnlineVirtualColumnVo> view(OnlineVirtualColumn virtualColumn) {
        if (CommonUtil.existBlankArgument(virtualColumn.getVirtualColumnId())) {
            return R.fail(ErrorCodeEnum.ARGUMENT_NULL_EXIST.getErrorMessage());
        }
        OnlineVirtualColumn onlineVirtualColumn =
                onlineVirtualColumnService.getByIdWithRelation(virtualColumn.getVirtualColumnId(), MyRelationParam.full());
        if (onlineVirtualColumn == null) {
            return R.fail(ErrorCodeEnum.DATA_NOT_EXIST.getErrorMessage());
        }
        return R.data(OnlineVirtualColumnWrapper.build().entityVO(onlineVirtualColumn));
    }

    private R<Void> doVerify(
            OnlineVirtualColumn virtualColumn, OnlineVirtualColumn originalVirtualColumn) {
        if (!virtualColumn.getVirtualType().equals(VirtualType.AGGREGATION)) {
            return R.data(null);
        }
        if (CommonUtil.existBlankArgument(
                virtualColumn.getAggregationColumnId(),
                virtualColumn.getAggregationTableId(),
                virtualColumn.getDatasourceId(),
                virtualColumn.getRelationId(),
                virtualColumn.getAggregationType())) {
            String errorMessage = "数据验证失败，数据源、关联关系、聚合表、聚合字段和聚合类型，均不能为空！";
            return R.fail(errorMessage);
        }
        R verifyResult = onlineVirtualColumnService.verifyRelatedData(virtualColumn, null);
        if (!verifyResult.isSuccess()) {
            return R.fail(verifyResult.getMsg());
        }
        return R.data(null);
    }
}
